package tools;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.BufferedInputStream;

public class ReadGrd {

	/*
	 * fileName为数据全路径+文件名
	 * year为数据年份
	 * datalen为单天数据大小例如144×73×17×4
	 */
	public static int GetFileLength(String fileName,int datalen){
		int count = 0;
		File file = new File(fileName);
		if(!file.exists()) return 0;
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(file); 
            count = fis.available();
            System.out.println("文件size:"+String.valueOf(fis.available()/1000)+"k");
        }catch(IOException e1){   
            System.out.println("IO出错！");
        }
        return count/datalen;

	}
	
	public static float[][][][] GetdataGrd(String fileName,int lon,int lat,int layer){
		int datalen = lon*lat*layer*4;
		int days = GetFileLength(fileName,datalen);
		if(days == 0) return null;
		
		float[][][][] data = new float[lon][lat][layer][days];
		int count = 0;
		
		DataInputStream dis = null;

        try {
            System.out.println("以字节为单位读取文件内容，一次读多个字节：");
            // 一次读多个字节
			dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
            //dis=new DataInputStream(new FileInputStream(new File(fileName)));
            for(int day = 0 ; day < days ; day++)
            {
				//System.out.println("读取第"+day+"天的数据");
            	for(int lay = 0;lay <layer ; lay++)
            	{
            		for(int ilat = 0;ilat < lat; ilat++)
            		{
            			for(int ilon = 0;ilon < lon; ilon++)
            			{
            				data[ilon][ilat][lay][day] = dis.readFloat();
            			}
            		}
            	}
            }
            /*while (in.read(tempbytes) != -1) {
            	//if(count%100000 == 0) System.out.println(count);
            	data[count] = arr2float(tempbytes);
            	count++;
            }*/
            dis.close();
            System.out.println(count);
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e1) {
                }
            }
        }

		return data;
		//return null;
	}

}
